//
//  GHTTPConnection.m
//  Test
//
//  Created by geng on 2019/8/17.
//  Copyright © 2019 geng. All rights reserved.
//

#import "GHTTPConnection.h"
#import "HTTPMessage.h"
#import "HTTPDataResponse.h"
#import "HTTPLogging.h"
#import <AdSupport/ASIdentifierManager.h>
#import "base64.h"
#import <UIKit/UIKit.h>
#import "LMAppController.h"

#import "DeviceParam.h"

@implementation GHTTPConnection

- (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path{
    NSLog(@"supportsMethod method: %@ \n path:%@",method, path);
    if ([method isEqualToString:@"POST"]||[method isEqualToString:@"OPTIONS"]){
        // Let's be extra cautious, and make sure the upload isn't 5 gigs
        return YES;
    }

    return [super supportsMethod:method atPath:path];
}
- (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path{
    
    // Inform HTTP server that we expect a body to accompany a POST request
    if([method isEqualToString:@"POST"]||[method isEqualToString:@"OPTIONS"]) return YES;
    
    return [super expectsRequestBodyFromMethod:method atPath:path];
}
- (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path{
    NSLog(@"httpResponseForMethod method: %@ \n path:%@",method, path);
    
    
    if ([method isEqualToString:@"OPTIONS"]){
        
        NSData *responseData =[@"1" dataUsingEncoding:NSUTF8StringEncoding];
        return [[HTTPDataResponse alloc] initWithData:responseData];
    }
    if ([method isEqualToString:@"GET"]){
        if ([path isEqualToString:@"/getSysInfo.do"]) {
            NSDictionary *param = [self getParam];
            NSData *data = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
            NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSString *context = __BASE64(dataStr);
            NSData *responseData =[context dataUsingEncoding:NSUTF8StringEncoding];
            return [[HTTPDataResponse alloc] initWithData:responseData];
            
        }
        if ([path isEqualToString:@"/pingDevice.do"]) {
            
            NSString *dataStr = @"ok";
            NSString *context = __BASE64(dataStr);
            NSData *responseData =[context dataUsingEncoding:NSUTF8StringEncoding];
            return [[HTTPDataResponse alloc] initWithData:responseData];
            
        }
    }
    if ([method isEqualToString:@"POST"]){

        if ([path isEqualToString:@"/openAppStore.do"]) {
            NSData *requestData = [request body];
            NSString *requestBodyData  =[[NSString alloc] initWithData:requestData encoding:NSUTF8StringEncoding];
            
            requestBodyData = [base64 textFromBase64String:requestBodyData];
            NSData *data = [requestBodyData dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *tempDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSLog(@"%@", tempDic);
            NSString *toLocalParam = tempDic[@"localParam"];
            data = [toLocalParam dataUsingEncoding:NSUTF8StringEncoding];
            tempDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSString *content = tempDic[@"keyword"];
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            [pasteboard setString:content];
            
            BOOL result = [[LMAppController sharedInstance] openAppWithBundleIdentifier:@"com.apple.AppStore"];
            NSLog(@"%d",result);
            NSString * responseStr = @"{'msg':'打开成功','code':0}";
            if (result) {
                responseStr = @"{'msg':'打开失败','code':101}";
            }
            NSString *context = __BASE64(responseStr);
            
            NSData *responseData =[context dataUsingEncoding:NSUTF8StringEncoding];
            return [[HTTPDataResponse alloc] initWithData:responseData];
            
        }
        
        if ([path isEqualToString:@"/playApp.do"]) {
            NSData *requestData = [request body];
            NSString *requestBodyData  =[[NSString alloc] initWithData:requestData encoding:NSUTF8StringEncoding];
            
            requestBodyData = [base64 textFromBase64String:requestBodyData];
            NSData *data = [requestBodyData dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *tempDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            NSString *toLocalParam = tempDic[@"localParam"];
            data = [toLocalParam dataUsingEncoding:NSUTF8StringEncoding];
            tempDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSString *bundleid = [tempDic objectForKey:@"bundleid"];
//            bundleid = @"com.geng.circle";
            NSLog(@"bundleid %@",bundleid);
            BOOL result = [[LMAppController sharedInstance] openAppWithBundleIdentifier:bundleid];
            NSString * responseStr = @"{'msg':'应用启动成功','code':0}";
            if (!result) {
                responseStr = @"{'msg':'请先安装改应用','code':101}";
            }
            NSString *context = __BASE64(responseStr);
            
            NSData *responseData =[context dataUsingEncoding:NSUTF8StringEncoding];
            return [[HTTPDataResponse alloc] initWithData:responseData];
        }
        
        //HTTPLogVerbose(@"%@[%p]: postContentLength: %qu", THIS_FILE, self, requestContentLength);
        NSData *requestData = [request body];
        NSString *requestBodyData  =[[NSString alloc] initWithData:requestData encoding:NSUTF8StringEncoding];
        
        requestBodyData = [base64 textFromBase64String:requestBodyData];
        NSLog(@"data=%@",requestBodyData);
//        [self request:requestBodyData];
        
        NSData *data = [requestBodyData dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *tempDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSString *toLocalParam = tempDic[@"toLocalParam"];
        
        data = [toLocalParam dataUsingEncoding:NSUTF8StringEncoding];
        tempDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSString *urlStr = tempDic[@"url"];
        // 1.创建请求路径(url)
        NSURL *url = [NSURL URLWithString:urlStr];
        
        NSString *context = __BASE64(requestBodyData);
        // 2.通过请求路径(url)创建请求对象(request)
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setValue:@"application/encryp;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
        // 更改请求方法
        request.HTTPMethod = @"POST";
        // 设置请求体
        request.HTTPBody = [context dataUsingEncoding:NSUTF8StringEncoding];
        // 设置超时(5秒后超时)
        request.timeoutInterval = 5;
        // 设置请求头
        // [request setValue:@"iOS 9.0" forHTTPHeaderField:@"User-Agent"];
        
        // 3.向服务器发送异步请求
        //    NSURLSession *sharedSession = [NSURLSession sharedSession];
        
        //同步执行Http请求，获取返回数据
        NSURLResponse *response;
        NSError *error;
        NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        NSString *dataStr = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
        
        NSString *resultData = [base64 textFromBase64String:dataStr];
        NSLog(@"data=%@",resultData);
        
//        NSLog(@"httpResponseForMethod - method: %@  - body: %@ - path:%@", method,requestBodyData,path);
        NSData *responseData =[dataStr dataUsingEncoding:NSUTF8StringEncoding];
        return [[HTTPDataResponse alloc] initWithData:responseData];
    }

    return [super httpResponseForMethod:method URI:path];
}

- (void)prepareForBodyWithSize:(UInt64)contentLength
{
    
    
    // If we supported large uploads,
    // we might use this method to create/open files, allocate memory, etc.
}

- (void)processBodyData:(NSData *)postDataChunk
{
    
    
    // Remember: In order to support LARGE POST uploads, the data is read in chunks.
    // This prevents a 50 MB upload from being stored in RAM.
    // The size of the chunks are limited by the POST_CHUNKSIZE definition.
    // Therefore, this method may be called multiple times for the same POST request.
    
    BOOL result = [request appendData:postDataChunk];
    if (!result)
    {
        NSLog(@"%@[%p]: %@ - Couldn't append bytes!", THIS_FILE, self, THIS_METHOD);
    }
}

#pragma mark - 私有方法

//获取上行参数
- (NSDictionary *)getRequestParam:(NSData *)rawData
{
    if (!rawData) return nil;
    
    NSString *raw = [[NSString alloc] initWithData:rawData encoding:NSUTF8StringEncoding];
    NSMutableDictionary *paramDic = [NSMutableDictionary dictionary];
    NSArray *array = [raw componentsSeparatedByString:@"&"];
    for (NSString *string in array) {
        NSArray *arr = [string componentsSeparatedByString:@"="];
        NSString *value = [arr.lastObject stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [paramDic setValue:value forKey:arr.firstObject];
    }
    return [paramDic copy];
}

- (NSData *)preprocessResponse:(HTTPMessage *)response{
    //允许跨域访问
    [response setHeaderField:@"Access-Control-Allow-Origin" value:@"*"];
    [response setHeaderField:@"Access-Control-Allow-Credentials" value:@"true"];
    [response setHeaderField:@"Access-Control-Allow-Methods" value:@"POST, GET, OPTIONS"];
    [response setHeaderField:@"Access-Control-Max-Age" value:@"36000"];
    [response setHeaderField:@"Access-Control-Allow-Headers" value:@"Content-Type"];
    
    return [response messageData];
}

- (NSData *)preprocessErrorResponse:(HTTPMessage *)response{
    [response setHeaderField:@"Access-Control-Allow-Origin" value:@"*"];
    [response setHeaderField:@"Access-Control-Allow-Credentials" value:@"true"];
    [response setHeaderField:@"Access-Control-Allow-Methods" value:@"POST, GET, OPTIONS"];
    [response setHeaderField:@"Access-Control-Max-Age" value:@"36000"];
    [response setHeaderField:@"Access-Control-Allow-Headers" value:@"Content-Type"];
    
    return [response messageData];
}

- (void)request:(NSString *)context{
    
    
    NSData *data = [context dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *tempDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSString *toLocalParam = tempDic[@"toLocalParam"];
    
    data = [toLocalParam dataUsingEncoding:NSUTF8StringEncoding];
    tempDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSString *urlStr = tempDic[@"url"];
    // 1.创建请求路径(url)
    NSURL *url = [NSURL URLWithString:urlStr];
    
    context = __BASE64(context);
    // 2.通过请求路径(url)创建请求对象(request)
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"application/encryp;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    // 更改请求方法
    request.HTTPMethod = @"POST";
    // 设置请求体
    request.HTTPBody = [context dataUsingEncoding:NSUTF8StringEncoding];
    // 设置超时(5秒后超时)
    request.timeoutInterval = 5;
    // 设置请求头
    // [request setValue:@"iOS 9.0" forHTTPHeaderField:@"User-Agent"];
    
    // 3.向服务器发送异步请求
//    NSURLSession *sharedSession = [NSURLSession sharedSession];
    
    //同步执行Http请求，获取返回数据
    NSURLResponse *response;
    NSError *error;
    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSLog(@"result %@",result);
    NSString *dataStr = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
    NSLog(@"data=%@",[base64 textFromBase64String:dataStr]);
//    NSURLSessionDataTask *dataTask = [sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        if (data && (error == nil)) {
//            // 网络访问成功
//            NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//            NSLog(@"data=%@",[base64 textFromBase64String:dataStr]);
//
//        } else {
//            // 网络访问失败
//            NSLog(@"error=%@",error);
//        }
//    }];
//    [dataTask resume];
}

-(NSDictionary*)getParam{
    
    NSString *deviceModel = [DeviceParam getModel];
    NSString *isVPN = [DeviceParam getIsVPN];
    NSString *ssid = [DeviceParam getSSID];
    NSString *bundid = [DeviceParam getBundleID];
    NSString *versionName = [DeviceParam getVersionName];
    NSString *versionCode = [DeviceParam getVersionCode];
    NSString *platform = [DeviceParam getPlatform];
    NSString *isBreak = [DeviceParam getIsBreak];
    NSString *ip = [DeviceParam getIP];
    NSString *sysVersion = [DeviceParam getSystemVersion];
    NSString *sim =[DeviceParam getIsSIMInstalled];
    NSString *netType = [DeviceParam getNetType];
    NSString *idfa = [DeviceParam getIDFA];
    NSString *idfv = [DeviceParam getIDFV];
    NSString *uuid = [DeviceParam getUUIDInKeychain];
    NSDictionary *param = @{@"deviceModel":deviceModel,
                            @"isVPN":isVPN,
                            @"ssid":ssid,
                            @"bundid":bundid,
                            @"versionName":versionName,
                            @"versionCode":versionCode,
                            @"platform":platform,
                            @"isBreak":isBreak,
                            @"ip":ip,
                            @"sysVersion":sysVersion,
                            @"sim":sim,
                            @"netType":netType,
                            @"deviceId":idfa,
                            @"uuid":uuid
                            };
    
    NSLog(@"model: %@", deviceModel);
    NSLog(@"isvpn: %@", isVPN);
    NSLog(@"ssid: %@", ssid);
    NSLog(@"bundID :%@", bundid);
    NSLog(@"versionName: %@",versionName);
    NSLog(@"versionCode: %@",versionCode);
    NSLog(@"platform: %@", platform);
    NSLog(@"isBreak: %@", isBreak);
    NSLog(@"ip: %@", ip);
    NSLog(@"sysVersion: %@", sysVersion);
    NSLog(@"sim: %@", sim);
    NSLog(@"netType: %@", netType);
    NSLog(@"idfa: %@", idfa);
    NSLog(@"idfv: %@", idfv);
    NSLog(@"uuid: %@", uuid);
    
    return param;
    
}
@end
